<template>
  <div>
    <div class="page">
      <DynamicForm
        v-show="showSearch"
        ref="queryRef"
        v-model="queryParams"
        :config="formConfig"
        :items="formItems"
        :inline="true"
        :dict-data="{ case_source, work_status }"
        @submit="handleQuery"
        @reset="resetQuery">
        <template #dateRange="{ formData }">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 18vw" />
        </template>
      </DynamicForm>
      <el-row :gutter="10" class="mb10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['registrationcase:registrationcase:add']">
            新增案件
          </el-button>
          <el-button
            :disabled="exportDis"
            type="warning"
            plain
            icon="Download"
            @click="handleExport(1)"
            v-hasPermi="['registrationcase:registrationcase:export']">
            导出授权委托书
          </el-button>
          <el-button
            :disabled="exportDis"
            type="warning"
            plain
            icon="Download"
            @click="handleExport(2)"
            v-hasPermi="['registrationcase:registrationcase:export']">
            导出送达信息确认书
          </el-button>
          <el-button
            :disabled="exportDis"
            type="warning"
            plain
            icon="Download"
            @click="handleExport(3)"
            v-hasPermi="['registrationcase:registrationcase:export']">
            导出立案审批表
          </el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>
      <Table
        v-loading="loading"
        :data="tableData"
        :columns="newColumns"
        :dictData="{ work_status, caseTypeList, case_source }"
        @selection-change="handleSelectionChange"
        border>
        <template #index="{ $index }">
          {{ queryParams.pageNum * queryParams.pageSize - queryParams.pageSize + $index + 1 }}
        </template>
        <template #caseStatus="{ row }">
          <el-tag
            :type="
              row.status === '1'
                ? 'info'
                : row.status === '2'
                ? 'primary'
                : row.status === '3'
                ? 'warning'
                : row.status === '4'
                ? 'success'
                : row.status === '6'
                ? 'danger'
                : 'info'
            ">
            {{ caseStatus.find(item => item.value === row.status)?.label }}
          </el-tag>
        </template>
        <template #action="{ row }">
          <el-button
            v-hasPermi="['registrationcase:registrationcase:query']"
            link
            type="primary"
            icon="view"
            @click="handleEdit(row, 'view')">
            查看
          </el-button>
          <el-button
            v-if="Number(row.status) === 1 || !row?.status"
            v-hasPermi="['registrationcase:registrationcase:edit']"
            link
            type="primary"
            icon="Edit"
            @click="handleEdit(row, 'edit')">
            修改
          </el-button>
          <!-- <el-button v-if="row.caseProcedure !== '1'" link type="primary" icon="RefreshLeft" @click="handleRevoke(row)">
            撤回
          </el-button> -->
          <el-button link type="primary" icon="view" @click="handlePreview(row)">预览</el-button>
          <el-button link type="primary" icon="upload" @click="handleUpload(row)">上传附件</el-button>
          <el-button
            v-if="Number(row.applyStatus) < 1 || !row?.applyStatus"
            v-hasPermi="['registrationcase:registrationcase:remove']"
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </Table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList" />

      <!-- 上传附件弹窗 -->
      <el-dialog title="上传附件" v-model="fileModal" width="1200px">
        <FileList v-if="fileModal" :fileUploadList="fileUploadList" />
        <template #footer>
          <div class="form-footer">
            <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
            <el-button @click="() => (fileModal = false)">取消</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 预览弹窗 -->
      <el-dialog v-model="previewVisible" title="案件预览" width="80%" append-to-body>
        <div class="tools-box">
          <el-icon @click="handleDownLoad"><Download /></el-icon>
        </div>
        <vue-office-docx :src="docxPreviewUrl" />
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import DynamicForm from '@/components/DynamicForm/index.vue'
import { ref, reactive, onMounted, getCurrentInstance, computed } from 'vue'
import Table from '@/components/Table'
import { createInput, createSelect, createSlot } from '@/components/DynamicForm/config'
import { useTableColumns } from './config'
import { useDeleteConfirm } from '@/hooks/useDeleteConfirm'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import FileUpload from '@/components/FileUpload/index.vue'
import FileList from '@/components/FileList/index.vue'
import VueOfficeDocx from '@vue-office/docx'
import {
  getRegistrationcase,
  registrationcasePreview,
  registrationcaseDetail,
  registrationcaseAddFiles,
  registrationcaseDelete,
  exportPenaltydecisions,
  exportDeliveryConfirmation,
  exportFilingApprovalForm,
} from '@/api/filingReview/register.js'
import useDictStore from '@/store/modules/dict'
import { downloadBlob } from '@/utils/download.js'

const router = useRouter()

const { proxy } = getCurrentInstance()
const { case_source } = proxy.useDict('case_source')
const { statusList: work_status, caseStatus } = useDictStore()

// 初始化删除确认 hook
const { confirmDeleteSingle, showDeleteConfirm } = useDeleteConfirm()
const caseTypeList = [
  { value: '1', label: '简易案件' },
  { value: '2', label: '一般案件' },
  { value: '3', label: '重大案件' },
]
const showSearch = ref(true)
const formConfig = {
  labelWidth: '100px',
  inline: true,
  keyup: true,
  buttonAlign: 'right',
  isSearch: true,
  buttons: [
    { text: '搜索', type: 'primary', action: 'submit' },
    { text: '重置', action: 'reset' },
  ],
}
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  partyName: undefined,
  caseSource: undefined,
  caseProcedure: undefined,
  params: {
    beginCreateTime: undefined,
    endCreateTime: undefined,
  },
})
const formItems = [
  createInput('当事人名称', 'partyName', {
    placeholder: '请输入当事人名称',
    style: { width: '220px' },
    props: {
      clearable: true,
    },
  }),
  createSelect('案件来源', 'caseSource', {
    placeholder: '请输入案件来源',
    style: { width: '220px' },
    props: {
      clearable: true,
    },
    dictKey: 'case_source',
    optionProps: {
      label: 'label',
      value: 'value',
      key: 'value',
    },
  }),
  createSelect('立案程序', 'caseProcedure', {
    placeholder: '请选择立案程序',
    style: { width: '220px' },
    props: {
      clearable: true,
    },
    options: caseTypeList,
  }),
  createSelect('审批状态', 'status', {
    placeholder: '请选择审批状态',
    style: { width: '220px' },
    props: {
      clearable: true,
    },
    dictKey: 'work_status',
  }),
  createSlot('登记时间', 'dateRange', {
    slotName: 'dateRange',
    style: { width: '220px' },
  }),
]
const dateRange = ref([])

// 查询表单
const handleQuery = () => {
  getList()
}
// 重置表单
const resetQuery = () => {
  dateRange.value = null
  getList()
}

// 新增
const handleAdd = () => {
  router.push({
    path: '/workbench/filingReview/registerDetail',
    query: {
      type: 'add',
    },
  })
}
// 控制导出
const exportDis = computed(() => {
  if (selectedRows.value.length) {
    return selectedRows.value.some(item => item?.applyStatus !== '5')
  } else {
    return true
  }
})
// 导出
const handleExport = async type => {
  const _ids = ids.value
  let res: any
  if (type === 1) {
    res = await exportPenaltydecisions(_ids)
  } else if (type === 2) {
    res = await exportDeliveryConfirmation(_ids)
  } else if (type === 3) {
    res = await exportFilingApprovalForm(_ids)
  }
  downloadBlob(res)
}

// 表格相关 start ======================================================
// 列显隐信息
const { columns, newColumns } = useTableColumns()
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
// 获取表格数据
async function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (dateRange.value && dateRange.value.length) {
    queryParams.value.params.beginCreateTime = dateRange.value[0]
    queryParams.value.params.endCreateTime = dateRange.value[1]
  } else {
    queryParams.value.params.beginCreateTime = undefined
    queryParams.value.params.endCreateTime = undefined
  }
  const res: any = await getRegistrationcase(queryParams.value)
  tableData.value = res.rows || []
  total.value = res.total || 0
  loading.value = false
}
// 选择行
const selectedRows = ref<any>({})
const ids = ref<any>([])
// 选择行变化
const handleSelectionChange = val => {
  console.log('选择行', val)
  ids.value = val.map(item => item.id)
  selectedRows.value = val
}

// 撤回接口
const revokeCase = async (id: string) => {
  console.log('撤回案件 ID:', id)
}
// 撤回案件
const handleRevoke = async (row: any) => {
  try {
    await showDeleteConfirm(() => revokeCase(row.id || row.caseId), {
      title: '撤回案件',
      message: '案件正在审批中，确定撤回？',
    })
  } catch (error) {
    // 用户取消删除
    console.log('用户取消删除案件')
  }
}
// 编辑 查看 撤回
const handleEdit = (row, type) => {
  router.push({
    path: '/workbench/filingReview/registerDetail',
    query: {
      id: row.id || row.caseId,
      type,
      procInsId: row.procInsId || '',
    },
  })
}
// 删除案件的 API 函数
const deleteCase = async caseId => {
  // 模拟 API 调用
  await registrationcaseDelete(caseId)
  console.log('删除案件 API 调用:', caseId)
  ElMessage.success('案件删除成功')
  // 删除后刷新列表
  await getList()
}
// 预览
const previewVisible = ref(false)
const docxPreviewUrl = ref('')
const fileBlob = ref<Blob | null>(null)
const previewRow = ref<any>(null)
const FileSaverRef = ref<any>(null)
const handlePreview = async row => {
  previewRow.value = row
  // 前端预览代码
  // import('docxtemplater').then(Docxtemplater => {
  //   import('pizzip').then(PizZip => {
  //     import('jszip-utils').then(JSZipUtils => {
  //       import('file-saver').then(FileSaver => {
  //         FileSaverRef.value = FileSaver
  //         // 获取模板文件
  //         JSZipUtils.getBinaryContent('/register.docx', (error, content) => {
  //           if (error) {
  //             throw error
  //           }
  //           // 创建PizZip实例，加载模板内容
  //           const zip = new PizZip.default(content)
  //           // 创建docxtemplater实例
  //           const doc = new Docxtemplater.default(zip)
  //           // 设置要替换的数据
  //           doc.setData({
  //             field1: row.field1,
  //             // 可添加更多需要替换的字段
  //           })
  //           try {
  //             // 渲染文档
  //             doc.render()
  //           } catch (err) {
  //             console.error('渲染文档失败:', err)
  //             return
  //           }
  //           // 生成文档内容
  //           fileBlob.value = doc.getZip().generate({
  //             type: 'blob',
  //             mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  //           })
  //           // 保存文件
  //           // FileSaver.saveAs(out, `案件-${row.field1}.docx`)
  //           // 预览
  //           docxPreviewUrl.value = URL.createObjectURL(fileBlob.value)
  //           previewVisible.value = true
  //         })
  //       })
  //     })
  //   })
  // })
  loading.value = true
  const res: any = await registrationcasePreview(row.id)
  if (!!res.msg) {
    window.open(res.msg)
  } else {
    ElMessage.warning('预览文件不存在')
  }
  loading.value = false
}

// 下载预览文件
const handleDownLoad = () => {
  FileSaverRef.value.saveAs(fileBlob.value, `案件-${previewRow.value.field1}.docx`)
}

// 上传附件
const fileModal = ref(false)
const fileUploadList = ref([])
const rowId = ref('')
const handleUpload = async row => {
  rowId.value = row.id
  const res = await registrationcaseDetail(row.id)
  fileUploadList.value = res.data.tregistrationCaseFilesList || []
  fileModal.value = true
}
// 上传附件
const handleUploadConfirm = async () => {
  await registrationcaseAddFiles({ id: rowId.value, tregistrationCaseFilesList: fileUploadList.value })
  ElMessage.success('保存成功')
  fileModal.value = false
}

// 删除单个案件
const handleDelete = async row => {
  try {
    await confirmDeleteSingle(() => deleteCase(row.id || row.caseId), ` "${row.partyName}" 的案件信息`)
  } catch (error) {
    // 用户取消删除
    console.log('用户取消删除案件')
  }
}

// 表格相关 end ======================================================

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.tools-box {
  position: absolute;
  right: 20px;
  top: 60px;
  z-index: 10;
  color: #fff;
  font-size: 26px;
  .el-icon {
    cursor: pointer;
    &:hover {
      color: var(--el-color-primary);
    }
  }
}
</style>
